package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.domain.AbilityPath;
import com.ruoyi.domain.Ability_ServiceInfor;
import com.ruoyi.domain.Ability_ServiceLimitingInfor;
import com.ruoyi.mapper.Ability_ServiceInforMapper;
import com.ruoyi.service.Ability_AbiltyService;
import com.ruoyi.service.Ability_ServiceLimitingService;
import com.ruoyi.service.IAbilityPathService;
import com.ruoyi.service.ServiceKong;
import org.apache.http.impl.execchain.ServiceUnavailableRetryExec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@Service("Ability_AbilityServiceImpl")
public class Ability_AbilityServiceImpl implements Ability_AbiltyService {
    @Autowired
    private Ability_ServiceInforMapper ability_ServiceInforMapper;
    @Autowired
    ServiceKong service;
    @Autowired
    Ability_ServiceLimitingService ability_ServiceLimitingService;
    @Autowired
    Ability_AbiltyService ability_AbilityService;
    @Autowired
    IAbilityPathService abilityPathService;
    @Override
    public List<Ability_ServiceInfor> selectAbility_ServiceInforList(Ability_ServiceInfor ability_ServiceInfor) {
        return ability_ServiceInforMapper.selectAbility_ServiceInforList(ability_ServiceInfor);
    }

    //中英文名，路由，主机
    @Override
    public int insertAbility_ServiceInfor(Ability_ServiceInfor ability_ServiceInfor) {


        String UUID = java.util.UUID.randomUUID().toString().replace("-", "");
        ability_ServiceInfor.setUUID(UUID);
        URL url = null;
        URL host = null;
        int message = 0;
        ability_ServiceInfor.setAllowgroup(ability_ServiceInfor.getServiceNameE());
        ability_ServiceInfor.setRejectgroup("");
        try {
            url = new URL(ability_ServiceInfor.getUrl());
            host = new URL(ability_ServiceInfor.getHost());
            ability_ServiceInfor.setAllowgroup("noit");

            String path = url.getPath();
            AbilityPath abilityPath = abilityPathService.checkPathUnique(path);
            if(abilityPath!=null){
                return -300;
            }else {
                abilityPath = new AbilityPath();
                abilityPath.setPath(path);
                abilityPath.setSid(UUID);
                abilityPath.setSname(ability_ServiceInfor.getServiceNameE());
                try {
                    abilityPathService.insertAbilityPath(abilityPath);
                }catch (Exception e){
                    return -300;
                }

            }
            message = ability_ServiceInforMapper.insertAbility_ServiceInfor(ability_ServiceInfor);
        } catch (Exception e) {
            System.out.println("URL/host格式错误");
            message = 0;
            e.printStackTrace();
            return -999;
        }
        return message;

    }

    @Override
    public int updateAbility_ServiceInfor(Ability_ServiceInfor ability_ServiceInfor) {

        Ability_ServiceInfor infor = selectAbility_ServiceInforById(ability_ServiceInfor.getUUID());
        if (infor.getStatus() == 1||infor==null){
            return -100;
        }
        URL url = null;
        URL host = null;
        try {
            url = new URL(ability_ServiceInfor.getUrl());
            host = new URL(ability_ServiceInfor.getHost());
        } catch (Exception e) {
            System.out.println("URL/host格式错误");
            e.printStackTrace();
            return -999;
        }
        String path = url.getPath();
       try {
           AbilityPath abilityPath=new AbilityPath();
           abilityPath.setPath(path);
           abilityPath.setSid(ability_ServiceInfor.getUUID());
           abilityPathService.updateAbilityPath(abilityPath);
       }catch (Exception e){
           return -300;
       }

        Ability_ServiceLimitingInfor ability_ServiceLimitingInfor = new Ability_ServiceLimitingInfor();
        ability_ServiceLimitingInfor.setLevelgroup(ability_ServiceInfor.getLevelgroup());
          ability_ServiceLimitingInfor.setSid(ability_ServiceInfor.getUUID());
         ability_ServiceLimitingService.updateAbility_ServiceLimitingInforBySid(ability_ServiceLimitingInfor);
        if (ability_ServiceInfor.getUUID() != null) {

            return ability_ServiceInforMapper.updateAbility_ServiceInfor(ability_ServiceInfor);
        }
        return 0;
    }

    @Override
    public int deleteAbility_ServiceInforById(String id) {

        Ability_ServiceInfor ability_ServiceInfor = selectAbility_ServiceInforById(id);
        if(ability_ServiceInfor.getStatus() == 1){
            return -100;
        }
        if(ability_ServiceInfor==null){
            return -200;
        }
       ability_ServiceLimitingService.delteAbility_ServiceLimitingInforBySid(ability_ServiceInfor.getUUID());
        if (id != null) {
            return ability_ServiceInforMapper.deleteAbility_ServiceInforById(id);
        }
        return 0;
    }

    @Override
    public Ability_ServiceInfor selectAbility_ServiceInforById(String id) {
        return ability_ServiceInforMapper.selectAbility_ServiceInforById(id);
    }

    @Override
    public Ability_ServiceInfor selectAbility_ServiceInforByName(String name) {
        return ability_ServiceInforMapper.selectAbility_ServiceInforByName(name);
    }

    @Override
    public int ApprovedService(Ability_ServiceInfor abilityServiceInfor) {
        Ability_ServiceInfor Infor ;
        Infor=ability_ServiceInforMapper.selectAbility_ServiceInforById(abilityServiceInfor.getUUID());
        if(Infor==null){
            return -300;
        }
        abilityServiceInfor.setServiceNameE(Infor.getServiceNameE());
        if(Infor.getStatus() == 1){
            return -100;
        }
        if (Infor.getStatus()==-1){
             return -200;
        }
        abilityServiceInfor.setAllowgroup(abilityServiceInfor.getServiceNameE() + "allow");
        abilityServiceInfor.setStatus(1);
        int k = 1;
        //  System.out.println(abilityServiceInfor.getUUID());
        JSONObject CreateKongParam = new JSONObject();
        JSONObject Service = new JSONObject();
        JSONObject route = new JSONObject();
        String routepath = "";
        //service参数
        Service.put("name", abilityServiceInfor.getServiceNameE());
        String httphost = abilityServiceInfor.getHost();
        String httpurl = abilityServiceInfor.getUrl();
        try {
            new URL(httphost);
            new URL(httpurl);
            try {
                URL url = new URL(httphost);
                Service.put("host", url.getHost());
                Service.put("port", url.getPort());
                String path = url.getPath().equals("") ? "/" : url.getPath();
                Service.put("path", path);
                URL url2 = new URL(httpurl);
                routepath = url2.getPath().equals("") ? "/" : url2.getPath();
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            // 是有效的URL
        } catch (MalformedURLException e) {
            // 不是有效的URL
            System.out.println("不是有效的URL");
        }

        //acl参数
        JSONObject acl = new JSONObject();
        acl.put("name", "acl");
        JSONObject config = new JSONObject();
        JSONArray allow = new JSONArray();
        allow.add(abilityServiceInfor.getAllowgroup());
        config.put("allow", allow);
        acl.put("config", config);
        CreateKongParam.put("service", Service);
        CreateKongParam.put("acl", acl);

        String r ="";



        //   System.out.println(abilityServiceInfor.getUrl());
        JSONArray paths = new JSONArray();
        paths.add(routepath);
        paths.add("/"+abilityServiceInfor.getServiceNameE());
        JSONArray methods = new JSONArray();
        methods.add("GET");
        methods.add("POST");
        route.put("name", abilityServiceInfor.getServiceNameE() + "route");
        route.put("paths", paths);
        route.put("methods", methods);
        System.out.println(route);
        String routeR = "";
        try {
            r= service.createService(CreateKongParam);
            routeR=service.createServiceroute(route, abilityServiceInfor.getServiceNameE());
        }catch (Exception e){
            this.backupService(abilityServiceInfor);
            return -999;
        }
        JSONObject result = JSONObject.parseObject(r);
        if (result.get("service").equals("succeed") && result.get("acl").equals("succeed") && routeR.equals("succeed")) {
            int sl = ability_AbilityService.updateAbility_ServiceInfor(abilityServiceInfor);
            if (sl > 0) {
                return 1;
            } else {
                return 0;
            }
        }

        return 0;


    }

    @Override
    public int notApprovedService(Ability_ServiceInfor abilityServiceInfor) {
        abilityServiceInfor=ability_ServiceInforMapper.selectAbility_ServiceInforById(abilityServiceInfor.getUUID());
        Ability_ServiceInfor infor=new Ability_ServiceInfor();
        if(abilityServiceInfor.getStatus()==null){
            return -1;
        }
        int k=0;
        if (abilityServiceInfor.getStatus() == 0) {
            infor.setStatus(-2);
            infor.setUUID(abilityServiceInfor.getUUID());
             k = ability_ServiceInforMapper.updateAbility_ServiceInfor(infor);
        }
        return k;
    }

    @Override
    public void backupService(Ability_ServiceInfor abilityServiceInfor) {
        String cname=abilityServiceInfor.getServiceNameE();
        JSONObject route=new JSONObject();
        JSONObject server=new JSONObject();
        try {
           String r= service.getIt("services/"+cname+"/routes");
           route=JSONObject.parseObject(r);
        }catch (HttpClientErrorException e){
            e.printStackTrace();
             route=null;
        }
        if(route!=null){
            JSONArray routes=route.getJSONArray("data");
            JSONObject route1=routes.getJSONObject(0);
             service.deleteRoute(cname,route1.getString("id"));
        }

        service.deleteService(cname);
    }


}

